const {md5} = require('../utils/md5');

const fs = require('fs');
const request = require("superagent"); //导入请求模块
const path = require("path");
const {host} = require('../configs/config');

class FileCtl {
    async upload(ctx) {
        const file = ctx.request.files.file; // 获取上传文件
        const username = ctx.request.body.name;
        if (file.size != null) {
            // 创建可读流
            const reader = fs.createReadStream(file.path);
            var fileName = '.' + file.name.split('.').slice(-1);
            const name = md5(file.name) + fileName;
            let filePath = path.join(__dirname, '../', './public/uploads/') + username + '/';
            if (!fs.existsSync(filePath)) {
                fs.mkdirSync(filePath);
            }
            // 创建可写流
            const upStream = fs.createWriteStream(filePath + file.name);
            await reader.pipe(upStream);
            // 可读流通过管道写入可写流
            let data = {url: file.name};
            return ctx.body = data;
        } else {
            return ctx.body = {msg: "获取文件失败"}
        }
    }

    async start(ctx) {
        const parms = ctx.query;
        const parm = 'http://192.168.199.163:3000/uploads/zhangsan/' + parms.url;
        request
            .get(host + '/nemo_eval')
            .query({url: parm})
            .then(res => {
                console.log(res)
            });
        return ctx.body = {msg: "上传服务器成功"}

    }
    async music(ctx) {
        const id = ctx.request.query.id;
        const redisData = await new Promise((resolve, reject) => {
            client.select('1', function (err) {
                if (err) {
                    return resolve({code: -1})
                } else {
                    client.smembers(id, function (err, res) {
                        if (err) {
                            return resolve({code: -1})
                        } else {
                            return resolve({code: 200, data: res})
                        }
                    })
                }
            })
        });
        if (redisData.code === 200) {
            const new_json = [];
            for (let i = 0; i < redisData.data.length; i++) {

                new_json.push(JSON.parse(redisData.data[i]))
            }
            ctx.body = {code: 200, data: new_json}
        } else {
            ctx.body = {code: -1}
        }

    }

}

module.exports = new FileCtl();
